module imagelib;
import std.stdio,std.base64;
import std.format, std.conv;
import core.stdc.errno;
import std.exception;

///取得图片的类型
string getImageType(string filename)
{
	string imgHexTag;
	try
	{
		auto f = File(filename, "r"); // open for read
		auto buf = f.rawRead(new char[4]);
		scope (exit)
			f.close();
		string s = buf.to!string;
		string sHex;
		foreach (c; s)
			sHex ~= format("%x", c);
		//imgHexTag = sHex;
		switch (sHex)
		{
		case "ffd8ffe0":
			imgHexTag = "jpg";
			break;
		case "89504e47":
			imgHexTag = "png";
			break;
		case "47494638":
			imgHexTag = "gif";
			break;
		default:
			imgHexTag = "fail";
		}
	}
	catch (ErrnoException ex)
	{
		switch (ex.errno)
		{
		case EPERM:
		case EACCES:
			// Permission denied
			break;

		case ENOENT:
			// File does not exist
			imgHexTag = "File does not exist";
			break; 
		default:
			// Handle other errors
			break;

		}
	}

	return imgHexTag;
}

/// imageEncodeBase64
string imageEncodeBase64(string filename,string imgType)
{
	string result="";
	try
	{
		auto c=new ubyte[1024*1024*20];    //20 Megabyte buffer
		auto f = File(filename, "r"); // open for read
		auto buf = f.rawRead(c);
		scope (exit)
				f.close();
		const(char)[] encoded = Base64.encode(buf);
		result= format("data:image/%1$s;base64,%2$s",imgType,encoded);
	}
	catch (ErrnoException ex)
	{
		switch (ex.errno)
		{
		case EPERM:
		case EACCES:
			// Permission denied
			break;

		case ENOENT:
			// File does not exist
			result = "File does not exist";
			break; 
		default:
			// Handle other errors
			break;
		}
	}
	return result;
}

void writeBase64(string filename,string filebody){
	try
	{
	auto f = File(filename~".base64", "w"); 
	f.rawWrite(filebody);
	scope (exit)
			f.close();
	}
	catch (ErrnoException ex)
	{
		switch (ex.errno)
		{
		case EPERM:
		case EACCES:
			// Permission denied
			break;

		case ENOENT:
			// File does not exist
			break; 
		default:
			// Handle other errors
			break;
		}
	}
}